package com.kirk.crawler.driver;

import com.kirk.crawler.constant.ResourceConstants;
import com.kirk.crawler.constant.SystemConstants;
import com.kirk.crawler.handler.CrawlerToolLoginHandler;
import com.kirk.crawler.ui.CrawlerToolLogin;
import com.kirk.crawler.utils.FileUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.swing.*;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.channels.FileLock;
import java.util.ArrayList;
import java.util.List;

/**
 *  <p> RunDriver.java </p>
 *
 * @Author      kirkliu
 * @Date        2020-08-29 22:25
 * @version     1.0.0
 * @Description 程序启动驱动类
 */
public class RunDriver {

    protected static final Log logger = LogFactory.getLog(RunDriver.class);

    private static String lockFile = SystemConstants.SYSTEM_ROOT_PATH + "/lock.lock";

    //文件锁
    private static FileLock lock = null;

    // 组件定义
    private static CrawlerToolLogin login;

    //程序启动入口
    public static void main(String[] args) {
        if(!isRunning()){
            checkUpdate();
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    login = new CrawlerToolLoginHandler();
                    login.setVisible(true);
                }
            });
        }
    }


    /**
     * 检查系统是否已经启动
     * @return 状态值 true 表示启动 false 表示未启动
     */
    private static boolean isRunning() {
        try {
            File flagFile = new File(lockFile);
            logger.info("程序启动锁定文件路径：" + flagFile.getAbsolutePath());
            if (!flagFile.exists()){
                flagFile.createNewFile();
            }
            lock = new FileOutputStream(lockFile).getChannel().tryLock();
            if (lock == null){
                return true;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }


    /**
     * 版本更新检查
     */
    private static void checkUpdate(){
        logger.info("开始版本更新检查,路径为:" + ResourceConstants.UPDATE_FILE);
        if(FileUtils.checkFileIsexists(ResourceConstants.UPDATE_FILE)){
            List<File> fileList = new ArrayList<File>();
            FileUtils.getAllFiles(new File(ResourceConstants.UPDATE_DIR),fileList);
            String newFilePath = "";
            if(!CollectionUtils.isEmpty(fileList)){
                for(File f : fileList){
                    // 如果文件存在，或者文件名为空，或者有相同的文件前缀，跳过后面执行
                    if(ResourceConstants.UPDATE_FILE_NAME.equals(FilenameUtils.getName(f.getAbsolutePath()))
                            || StringUtils.isBlank(f.getAbsolutePath())
                            || FilenameUtils.getName(f.getAbsolutePath()).contains(ResourceConstants.UPDATE_FILE_NAME_PRE)){
                        logger.info("跳过当前文件：" + f.getAbsolutePath());
                        continue;
                    }
                    newFilePath = f.getAbsolutePath().replace(ResourceConstants.PACKAGE_UPDATE + SystemConstants.SYSTEM_SEPARATOR, "");
                    logger.info("====更新文件：" + f.getAbsolutePath());
                    logger.info("====更新后文件路径：" + newFilePath);
                    // 将文件移到上一级目录
                    FileUtils.deleteFile(newFilePath);
                    FileUtils.createFile(f,newFilePath, false);
                    FileUtils.deleteFile(f.getAbsolutePath(),true);
                }
                //删除更新文件目录
                //FileUtils.deleteFile(ResourceConstants.UPDATE_FILE);
                FileUtils.deleteAllFile(ResourceConstants.UPDATE_DIR);
            }
        }
    }
}
